package com.example.service.impl;

import ch.qos.logback.classic.Logger;
import com.example.entity.Elevator;
import com.example.entity.MessageNotice;
import com.example.entity.PointDefend;
import com.example.entity.authority.SystemUser;
import com.example.entity.maintenance.DebrisHalfMon;
import com.example.entity.maintenance.EscalatorHalfMon;
import com.example.entity.maintenance.HydpressHalfMon;
import com.example.entity.maintenance.TractionHalfMon;
import com.example.ext.entity.ExtMessageNotice;
import com.example.mapp.*;
import com.example.service.MessageNoticeService;
import com.example.util.JpushUtil;
import com.example.util.ResultUtil;
import com.example.util.SystemPointUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by simon on 2017/10/12.
 */
@Service
public class MessageNoticeServiceImpl implements MessageNoticeService {

    private final static Logger logger = (Logger) LoggerFactory.getLogger(MessageNoticeServiceImpl.class);

    private static String appkey = "9e2d6b6f2387933a6983f7a5";

	private static String masterSecret = "d9c3da06f2102e5c3c02f207";

    @Autowired
    private MessageNoticeMapp messageNoticeMapp;

    @Autowired
    private SysUserMapp sysUserMapp;

    @Autowired
    private TractionMapp tractionMapp;

    @Autowired
    private EscalatorMapp escalatorMapp;

    @Autowired
    private HydpressMapp hydpressMapp;

    @Autowired
    private DebrisMapp debrisMapp;
    
	@Autowired
	private PromotionMapp promotionMapp;
	
	@Autowired
	private ElevatorMapp elevatorMapp;

    @Autowired
    private PointFlowMapp pointFlowMapp;
    /**
     * 插入通知消息
     * @param messageNotice
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> add(MessageNotice messageNotice) {
        try{
            String receivePartyId = messageNotice.getReceivePartyId();
            List<SystemUser> userList = sysUserMapp.queryByPartyId(receivePartyId);
            if(userList!=null){
                for ( int i=0; i<userList.size(); i++ ) {
                    messageNotice.setReceiveUserId(userList.get(i).getId()+"");
                    messageNoticeMapp.add(messageNotice);
                }
            }

        }catch(Exception e){
            logger.error("消息添加失败！",e);
            return ResultUtil.returnError("消息添加失败！",null);
        }

        return ResultUtil.returnSuccess("添加成功",null);
    }

    /**
     * 机构批量发通知
     * @param param
     * @return
     */
    @Override
    @Transactional
	public Map<String, Object> batchMsg(Map<String, Object> param) {
		String content = param.get("content") + "";
		String title = param.get("title") + "";
		String sendUserId = param.get("sendUserId") + "";
		String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		try {
			List<Map<String, Object>> list = messageNoticeMapp.findUserInfos(param);
            List<String> deviceIds = new ArrayList<>();
			for (Map<String, Object> tmp : list) {
				if(!deviceIds.contains(tmp.get("register_id") + "")){
                    MessageNotice msg = new MessageNotice();
                    msg.setTitle(title);
                    msg.setContent(content);
                    msg.setSendUserId(sendUserId);
                    msg.setReceiveUserId(tmp.get("user_id") + "");
                    msg.setIsRead("0");
                    msg.setNoticeTime(noticeTime);
                    msg.setReceivePartyId(tmp.get("party_id") + "");
                    messageNoticeMapp.add(msg);
                    if (null == tmp.get("register_id") || "".equals(tmp.get("register_id"))) {
                        continue;
                    }
                    deviceIds.add(tmp.get("register_id") + "");
                }
			}
            JpushUtil js = new JpushUtil(appkey, masterSecret, content, title);
			if(deviceIds != null && deviceIds.size() > 0 ){
                js.sendPushAll(true, deviceIds);
            }
		} catch (Exception e) {
			logger.error("消息添加失败！", e);
			return ResultUtil.returnError("消息添加失败！", null);
		}

		return ResultUtil.returnSuccess("添加成功", null);
	}

    /**
     * 更新阅读状态
     * @param map
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> updateReadState(Map<String, Object> map) {

        // 定义维保工作人员Id
        String maintenanceId1 = "";
        String maintenanceId2 = "";
        Elevator useAdministrator = new Elevator();


        try {
            // 更新消息表里的标志
            int i = messageNoticeMapp.updateReadState(map);
            if(map.get("elevatoriMonId")!=null){
            	Elevator elevator = new Elevator();
                // 1 代表 曳引与强制驱动电梯
                if(map.get("elevatoriType").equals("1")){
                    // 更新半月保数据表
                    tractionMapp.updateEscalatorHalfMon(map);
					TractionHalfMon tractionHalfMon = tractionMapp.queryTractionHalfMon(Long.valueOf((String) map.get("elevatoriMonId")));
                    // 得到电梯信息
					elevator = elevatorMapp.queryByElevatorNum(tractionHalfMon.getElevatorNum());
                    // 得到维保人员1、2
                    maintenanceId1 = tractionHalfMon.getMaintenanceUserId1();
                    maintenanceId2 = tractionHalfMon.getMaintenanceUserId2();
                }
                // 2 代表 液压驱动电梯
                if(map.get("elevatoriType").equals("2")){
                    hydpressMapp.updateEscalatorHalfMon(map);
					HydpressHalfMon hydpressHalfMon = hydpressMapp.queryHydpressHalfMon((String) map.get("elevatoriMonId"));
					elevator = elevatorMapp.queryByElevatorNum(hydpressHalfMon.getElevatorNum());

                    // 得到维保人员1、2
                    maintenanceId1 = hydpressHalfMon.getMaintenanceUserId1();
                    maintenanceId2 = hydpressHalfMon.getMaintenanceUserId2();
                }
                // 3 代表 杂物电梯
                if(map.get("elevatoriType").equals("3")){
                    debrisMapp.updateDebrisHalfMon(map);
					DebrisHalfMon debrisHalfMon = debrisMapp.queryDebrisHalfMon(Long.valueOf((String) map.get("elevatoriMonId")));
					elevator = elevatorMapp.queryByElevatorNum(debrisHalfMon.getElevatorNum());

                    // 得到维保人员1、2
                    maintenanceId1 = debrisHalfMon.getMaintenanceUserId1();
                    maintenanceId2 = debrisHalfMon.getMaintenanceUserId2();
                }
                // 4 自动扶梯与自动人行道
                if(map.get("elevatoriType").equals("4")){
                    escalatorMapp.updateEscalatorHalfMon(map);
					EscalatorHalfMon escalatorHalfMon = escalatorMapp.queryEscalatorHalfMon(Long.valueOf((String) map.get("elevatoriMonId")));
					elevator = elevatorMapp.queryByElevatorNum(escalatorHalfMon.getElevatorNum());

                    // 得到维保人员1、2
                    maintenanceId1 = escalatorHalfMon.getMaintenanceUserId1();
                    maintenanceId2 = escalatorHalfMon.getMaintenanceUserId2();
                }
                useAdministrator = elevator;
            }
        }catch(Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("更新阅读状态失败",e);
            return ResultUtil.returnError("更新阅读状态失败",null);
        }finally {
            // 当电梯信息不为空时，进行积分判断，电梯为空，为提醒信息
            if(null != useAdministrator && null != useAdministrator.getSafeUserId()){
                // 获取缓存
                PointDefendInfoCache infoCache = new PointDefendInfoCache();
                // 获取维保人员的积分规则
                PointDefend defend = infoCache.getKeyByValue("submit_maintenan_record");

                // 获取维保用户1，计算积分
                Map<String, Object> maps = pointFlowMapp.findUserInfoByUserId(Long.valueOf(maintenanceId1));
                long mark = (long) maps.get("mark");
                int round = (int) (mark + defend.getMark());
                // 更新用户信息总积分
                String userId = maps.get("userId").toString();
                int i1 = pointFlowMapp.updateMark(round, userId);

                String userName = maps.get("userName").toString();
                String partyName = maps.get("partyName").toString();
                SystemPointUtil.insertFlow(pointFlowMapp, i1, defend, round, userName, partyName, "维保员1"+maintenanceId1+"提交半月保维保记录");

                // 获取维保用户2，计算积分
                Map<String, Object> map2 = pointFlowMapp.findUserInfoByUserId(Long.valueOf(maintenanceId2));
                long mark2 = (long) map2.get("mark");
                int round2 = (int) (mark2 + defend.getMark());
                // 更新用户信息总积分
                String userId2 = map2.get("userId").toString();
                int i2 = pointFlowMapp.updateMark(round2, userId2);

                String userName2 = map2.get("userName").toString();
                String partyName2 = map2.get("partyName").toString();
                SystemPointUtil.insertFlow(pointFlowMapp, i2, defend, round2, userName2, partyName2, "维保员2"+maintenanceId2+"提交半月保维保记录");


                // 获取电梯安全管理员的积分规则
                PointDefend safeDefend = infoCache.getKeyByValue("sure_maintenance_selfcheck_record");
                Map<String, Object> usermaps = pointFlowMapp.findUserInfoByUserId(useAdministrator.getSafeUserId());
                long usermark = (long) usermaps.get("mark");
                int userround = (int) (usermark + safeDefend.getMark());

                // 更新用户信息总积分
                String userUserId = usermaps.get("userId").toString();
                int i3 = pointFlowMapp.updateMark(userround, userUserId);
                SystemPointUtil.insertFlow(pointFlowMapp, i3, safeDefend, userround, usermaps.get("userName").toString(), usermaps.get("partyName").toString(), "确认维保记录");

                // 更新维保单位的积分

                PointDefend defendUnit = infoCache.getKeyByValue("submit_maintenan_record_units");
                Map<String, Object> mapParty = pointFlowMapp.findUserInfo(useAdministrator.getMaintenancePartyId());
                long partyMark = (long) mapParty.get("mark");
                int partyRound = (int) (partyMark + defendUnit.getMark());

                String partyId = mapParty.get("userId").toString();
                int i4 = pointFlowMapp.updateMark(partyRound, partyId);
                SystemPointUtil.insertFlow(pointFlowMapp, i4, defendUnit, partyRound, mapParty.get("userName").toString(), mapParty.get("partyName").toString(), "维护保养和定期自行检查加单位积分");

            }
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    public Map<String, Object> deleteById(String id) {
        return null;
    }

    @Override
    public Map<String, Object> queryList(ExtMessageNotice extMessageNotice) {

        List<ExtMessageNotice> list =null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
//            Page<ExtMessageNotice> page = PageHelper.startPage(extMessageNotice.getCurrentPage(), extMessageNotice.getPageSize());
            list = messageNoticeMapp.queryList(extMessageNotice);
            int total = messageNoticeMapp.countList(extMessageNotice);
            map.put("list",list);
            map.put("total",total);

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",map);

    }

    @Override
    public Map<String, Object> querySendList(ExtMessageNotice extMessageNotice) {

        List<ExtMessageNotice> list =null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            Page<ExtMessageNotice> page = PageHelper.startPage(extMessageNotice.getCurrentPage(), extMessageNotice.getPageSize());
            list = messageNoticeMapp.querySendList(extMessageNotice);
            map.put("list",list);
            map.put("total",page.getTotal());

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",map);

    }


    @Override
    public Map<String, Object> findById(String id) {
        MessageNotice messageNotice = null;
        try{
             messageNotice = messageNoticeMapp.findById(id);
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",messageNotice);
    }
}
